import React, { Component } from 'react';
import { Button, Table, message, Input } from 'antd';
import { DownloadOutlined, SearchOutlined } from '@ant-design/icons';
import axios from 'axios'
import { Link } from 'react-router-dom'
import ExportJsonExcel from "js-export-excel";
class DianPuTable extends Component {
  constructor(props) {
    super(props)
    this.state = {
      size: 'large',
      selectedRowKeys: [],
      list: this.props.getList,
      pageSize: 5,
      currentPage: 1,
      inputValue: '',
    }
  }

  //生命周期获取数据
  componentDidMount() {
    this.getData().then(data => {
      this.setState({
        list: [...data]
      }, () => {
        // console.log(this.state.list);
      })
    }).catch(err => {
      console.log(err);
    })
  }
  //表格
  onSelectChange = selectedRowKeys => {
    console.log('selectedRowKeys changed: ', selectedRowKeys);
    this.setState({ selectedRowKeys });
  };
  changePage(current) {
    this.setState({
      currentPage: current
    })
  }
  //获取表格数据
  getData() {
    return new Promise((resolve, reject) => {
      axios.get(`/api/admin/shopView/page`).then((res) => {
        if (res.data.code === 0) {
          // console.log(res.data.data.list);
          this.shipei(res.data.data.list)
          resolve(res.data.data.list)
        } else {
          reject()
        }
      })
    })
  }
  //适配
  shipei(arr) {
    arr.forEach((item, index) => {
      item.shopStatus = item.shopStatus === 0 ?
        '待审核' : item.shopStatus === 1 ?
          '已认证' : '已驳回'
      item['key'] = index + 1
    })
    return arr
  }
  //搜索
  sousuo = () => {
    let config = {
      headers: {
        "Content-Type": "application/json;charset=UTF-8",
      },
    };
    let data = new FormData();
    data.append("str", this.state.inputValue);
    axios.post('/api/admin/attestation/shopSearch', data, config).then(res => {
      if (res.data.code === 0 && res.data.data.list.length > 0) {
        message
          .loading('查询中..', 1)
          .then(() => {
            message.success(' 查询成功', 2.5)
            this.setState({
              list: this.shipei(res.data.data.list)
            })
          })

      } else {
        message
          .loading('查询中..', 1)
          .then(() => {
            message.warning(' 无数据', 2.5)
          })
      }
    }).catch(err => {
      message
        .loading('查询中..', 1)
        .then(() => {
          message.error('后台数据错误', 2.5)
        })
    })
  }
  //输入
  shuru = (e) => {
    this.setState({
      inputValue: e.target.value
    })
  }
  //重置
  reset = () => {
    this.setState({
      inputValue: ''
    })
    this.getData().then(data => {
      this.setState({
        list: [...data]
      }, () => {
        // console.log(this.state.list);
      })
    }).catch(err => {
      console.log(err);
    })
  }
  //导出
  handleExportCurrentExcel = () => {
    //ExcelData为后端返回的data数组
    if (this.state.selectedRowKeys.length === 0) {
      message.warning(' 请勾选需要导出的数据', 2.5)
    } else {
      let ExcelData = []
      this.state.list.forEach(item => {
        this.state.selectedRowKeys.forEach(value => {
          if (item.key === value) {
            ExcelData.push(item)
          }
        })
      })
      let sheetFilter = ["key", "shopId", "shopName", "shopGroup", "shopStatus", "shopAccount", "userName"];
      let option = {};
      option.fileName = '店铺数据';
      option.datas = [
        {
          sheetData: ExcelData,
          sheetName: '店铺数据',
          sheetFilter: sheetFilter,
          sheetHeader: ['序号', '编号', '公司名称（店铺名称）', '经营类型', '状态', '商业登记证号码', '用户名称'],
          columnWidths: [10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10, 10]
        },
      ];

      var toExcel = new ExportJsonExcel(option); //new
      toExcel.saveExcel(); //保存
      message.success(' 导出成功', 2.5)
    }

  }

  render() {
    const { selectedRowKeys } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    const paginationProps = {
      showQuickJumper: false,
      showTotal: () => `共${this.state.list.length}条`,
      pageSize: this.state.pageSize,
      total: this.state.list.length,  //数据的总的条数
      onChange: (current) => this.changePage(current), //点击当前页码
    }
    const columns = [
      {
        title: '序号',
        dataIndex: 'key',
      },
      {
        title: '编号',
        dataIndex: 'shopId',
      },
      {
        title: '公司名称（店铺名称）',
        dataIndex: 'shopName',
      },
      {
        title: '经营类型',
        dataIndex: 'shopGroup',
      },
      {
        title: '状态',
        dataIndex: 'shopStatus',
      },
      {
        title: '商业登记证号码',
        dataIndex: 'shopAccount',
      },
      {
        title: '用户名称',
        dataIndex: 'userName',
      },
      {
        title: '操作',
        dataIndex: 'cz',
        key: 'x',
        render: (ip, row, index) => {
          let sdnStr = row.shopStatus.trim().toUpperCase();//小写转大写
          let shopId = row.shopId
          // console.log(shopId);
          if (sdnStr && sdnStr === '待审核') {
            return (
              <div className='caozuo' >
                <span><Link to={{ pathname: '/index/XQ', query: { shopId: shopId } }}>详情</Link></span>
                <span><Link to={{ pathname: '/index/XQ', query: { shopId: shopId, isshenpi: true } }}>审批</Link></span>
              </div >
            )
          } else {
            return (
              <div className='caozuo'>
                <span><Link to={{ pathname: '/index/XQ', query: { shopId: shopId } }}>详情</Link></span>
              </div>
            )
          }

        },
      },
    ];
    return (
      <>
        <div className='daochu'>
          <Button
            icon={<DownloadOutlined />}
            size={this.state.size}
            onClick={this.handleExportCurrentExcel}
          >
            导出
                 </Button>
          <div className='serach'>
            <div className='serchInput'>
              <Input
                size="large"
                placeholder="编号、名称、登记号码、账户名"
                value={this.state.inputValue}
                onInput={this.shuru}
                prefix={<SearchOutlined />}
              />
            </div>
            <div>
              <Button type="primary" danger onClick={this.sousuo}>
                搜索
            </Button>
            </div>
            <div>
              <Button onClick={this.reset}>
                重置
            </Button>
            </div>
          </div>
        </div>

        <div>
          <div style={{ marginBottom: 16 }}>
          </div>
          <Table
            rowSelection={rowSelection}
            columns={columns}
            dataSource={this.props.getList.length > 0 ? this.props.getList : this.state.list}
            pagination={paginationProps}
          />
        </div>

      </>
    );
  }
}

export default DianPuTable;